package com.huanzhidadi.java8inaction.chapter2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

@Slf4j
public class FileReadTest {

    /**
     * 从文件中读取一行内容
     * @return
     * @throws IOException
     */
    public static String processFile() throws IOException {
        Resource resource = new ClassPathResource("data.txt");
        try(BufferedReader br =
                    new BufferedReader(new FileReader(resource.getFile()))) {
            // 1、把br.readLine()这个行为进行参数化
            return br.readLine();
        }
    }

    public static void main(String[] args) throws IOException {
        String result = processFile();
        log.info(result);
        // 4、传递Lambda
        // 类型推断，可以进一步简化代码
        // 当Lambda仅有一个类型需要推断的参数时，参数名称两边的括号也可以省略
        result = processFile(br -> br.readLine() + br.readLine() + br.readLine());
        log.info(result);

        // Lambda表达式中调用的外层作用域中定义的局部变量，必须显式声明为final，或者事实上是final
        int num = 1122;
        Runnable r = () -> System.out.println(num);
        r.run();
        // num = 123;

    }

    /**
     * 3、执行一个行为
     * @param p
     * @return
     * @throws IOException
     */
    public static String processFile(BufferedReaderProcessor p) throws IOException {
        Resource resource = new ClassPathResource("data.txt");
        try(BufferedReader br =
                    new BufferedReader(new FileReader(resource.getFile()))) {
            return p.process(br);
        }
    }
}
